<template>
  <div>
    <!-- //面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" :v-model="searchVal" @change="searchFn">
            <el-button slot="append" icon="el-icon-search" @click="searchFn"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="isShow = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格数据渲染区域,根据用户基本信息数组渲染而来 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="demo">
            <el-switch v-model="demo.row.mg_state" @change="changeFn(demo.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="editObj">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              @click="editIsShowFn(editObj.row)"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              @click="delFn(editObj.row.id)"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                @click="fenRoles(editObj.row)"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 3, 5, 8]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userInfo.total"
      ></el-pagination>
    </el-card>

    <!-- 新增用户弹出框(用户信息) -->
    <el-dialog title="提示" :visible.sync="isShow" width="60%">
      <el-form :model="dataForm" status-icon :rules="fromRules" ref="ruleForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="dataForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="dataForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="pass">
          <el-input type="email" v-model="dataForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="pass">
          <el-input type="number" v-model="dataForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="sureFn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息弹出框 -->
    <el-dialog title="提示" :visible.sync="editIsShow" width="50%">
      <!-- 修改用户信息弹出表单 -->
      <el-form
        :model="editDataForm"
        status-icon
        :rules="fromRules"
        ref="editUserForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="editDataForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="editDataForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input type="number" v-model="editDataForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部确定及取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editIsShow = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfoFn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹出框 -->
    <el-dialog title="提示" :visible.sync="isFenShow" width="50%">
      <div>
        <p>当前用户:{{fenRolesInfo.username}}</p>
        <p>当前角色:{{fenRolesInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="sureRolseInfoId" placeholder="请选择">
            <el-option
              v-for="item in allUserRolseInfoList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isFenShow = false">取 消</el-button>
        <el-button type="primary" @click="sureFenRolse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//获取用户角色信息  API
import { getUserRolesAPI } from '@/api'
//获取用户基本信息相关API
import { getUserInfoAPI } from '@/api'
//修改用户状态API
import { editUserStateAPI } from '@/api'
//新增用户API
import { addUserAPI } from '@/api'
//修改用户信息API
import { editUserInfoAPI } from '@/api'
//删除用户信息API
import { delUserInfoAPI } from '@/api'
//重新分配用户角色信息API
import { fenUserRolseAPI } from '@/api'
export default {
  data() {
    return {
      userInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      editIsShow: false,
      userList: [],
      total: '',
      searchVal: '',
      isShow: false,
      //是否显示分配角色弹出框
      isFenShow: false,
      //分配角色相关信息
      fenRolesInfo: {},
      //确认分配角色信息的ID值
      sureRolseInfoId:null,
      //所有用户角色信息
      allUserRolseInfoList:[],
      //新增用户表单数据对象
      dataForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //修改用户表单信息
      editDataForm: {
        id: -1,
        username: '',
        email: '',
        mobile: ''
      },
      //校验规则
      fromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
          // { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
          // { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //获取用户信息,亦是表格相关数据
    async getUserInfo() {
      const { data } = await getUserInfoAPI(this.userInfo)
      this.userList = data.data.users
      console.log(this.userList)
      this.total = data.data.total
    },
    //页容量改变函数
    handleSizeChange(newPageSize) {
      this.userInfo.pagesize = newPageSize
      this.getUserInfo()
      console.log('页容量改变')
    },
    //当前页数改变处理函数
    handleCurrentChange(newPageSize) {
      this.userInfo.pagenum = newPageSize
      this.getUserInfo()
      console.log('当前页码改变')
    },
    //修改用户状态方法
    async changeFn(targetRowObj) {
      const { data } = await editUserStateAPI(
        targetRowObj.id,
        targetRowObj.mg_state
      )
      console.log(data)
      if (data.meta.msg != 200) {
        this.msg.error(data.meta.msg)
      } else {
        this.msg.success(data.meta.msg)
      }
    },
    searchFn() {
      this.userInfo.query = this.searchVal
      getUserInfoAPI()
      alert(45)
    },
    //确认新增按钮点击事件
    sureFn() {
      this.$refs.ruleForm.validate(async res => {
        if (!res) return this.msg.error('验证未通过')
        const { data } = await addUserAPI(this.dataForm)
        this.msg.error(data.meta.msg)
        console.log(data)
        if (data.meta.status != 201) return
        this.isShow = false
      })
    },
    //修改用户信息
    //作用域插槽传入当前行的相关数据信息
    editIsShowFn(editObj) {
      this.editIsShow = true
      console.log(editObj)
      this.editDataForm.id = editObj.id
      this.editDataForm.username = editObj.username
      this.editDataForm.email = editObj.email
      this.editDataForm.mobile = editObj.mobile
    },
    //确认修改用户信息函数
    async editUserInfoFn() {
      const { data } = await editUserInfoAPI(
        this.editDataForm.id,
        this.editDataForm.email,
        this.editDataForm.mobile
      )
      console.log(data)
      this.msg.warning(data.meta.msg)
      if (data.meta.status != 200) return
      this.getUserInfo()
      this.editIsShow = false
    },
    //删除用户信息函数
    async delFn(id) {
      const res = await this.tan('此操作将永久删除该用户, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.msg({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.msg({
            type: 'info',
            message: '已取消删除'
          })
        })
      console.log(res)
      if (res !== 'confirm') return this.msg.warning('取消删除成功!')
      const { data } = await delUserInfoAPI(id)
      console.log(data)
    },
    //获取用户所有角色信息函数
    async getUserRolseInfos(){
      const {data} = await getUserRolesAPI()
      if(data.meta.status != 200) return this.msg.error(data.meta.msg)
      this.allUserRolseInfoList = data.data
      console.log(data);
    },
    //分配角色按钮
    fenRoles(rolseObj) {
      this.isFenShow = true
      this.fenRolesInfo = rolseObj
      this.getUserRolseInfos()
    },
    //确定重新分配用户角色按钮事件
    async sureFenRolse(){
      this.isFenShow = false
      //用户id 标志是哪个用户
      let uId = this.fenRolesInfo.id
      //角色id  标志是哪个角色
      let rId = this.sureRolseInfoId
      const {data} = await fenUserRolseAPI(uId,rId)
      console.log(data);
      //局部刷新页面
      this.getUserInfo()
    }
  },
  async created() {
    this.getUserInfo()
  }
}
</script>

<style>
</style>